/*
 * @Author: your name
 * @Date: 2021-08-31 21:08:45
 * @LastEditTime: 2021-09-03 11:45:48
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \briup\5-javascript\13-forEach.js
 */

//foreach用法

var sum = 0;
var arr = [1, 2, 3, 4, 5, 6]
    //这样调用forEach方法，要把数组写在函数前
arr.forEach(function(value, index, arr) {
    sum += value;
});
console.log(sum); //21

//等价于下面普通版for循环

for (i = 0; i < this.length; i++) {
    sum += arr[i];
}
console.log(sum); //21


//forEach 对数组中的每一运行给定的函数,没有返回值，常用来遍历元素
Array.prototype.myForEach = function(fn) {
    for (var i = 0; i < this.length; i++) {
        //不能写返回值，因为要多次遍历
        fn(i, this[i]);
    }
}
var arr1 = [10, 'hello', 'world', 20, 30];
arr1.myForEach(function(index, value, arr) {
    //打印索引下标和值
    console.log(index, value); //0 10 1 hello 2 world 3 20 4 30
});